package com.me.myFramework.myAop.aop400;

import org.aspectj.weaver.tools.PointcutExpression;
import org.aspectj.weaver.tools.PointcutParser;
import org.aspectj.weaver.tools.PointcutPrimitive;

import java.lang.reflect.Method;
import java.util.HashSet;
import java.util.Set;

/**
 * AspectJ语法定义的切点
 *
 * @author ME
 * @date 2021/9/27
 */
public class AspectJExpressionPointcut implements MethodMatcher {

    /** 切点表达式 */
    private String expression;

    private static final Set<PointcutPrimitive> SUPPORTED_PRIMITIVES = new HashSet<>();
    static {
        SUPPORTED_PRIMITIVES.add(PointcutPrimitive.EXECUTION);
    }
    private final PointcutExpression pointcutExpression;

    public AspectJExpressionPointcut(String expression) {
        this.expression = expression;
        PointcutParser pointcutParser = PointcutParser.getPointcutParserSupportingSpecifiedPrimitivesAndUsingSpecifiedClassLoaderForResolution(SUPPORTED_PRIMITIVES, this.getClass().getClassLoader());
        pointcutExpression = pointcutParser.parsePointcutExpression(expression);
    }

    /**
     * 检查给定类对象是否匹配预设的切点表达式，后续拆分到 ClassFilter 接口中
     *
     * @param clazz    需要检查的类对象
     * @return 是否匹配切点表达式
     */
    public boolean matches(Class<?> clazz) {
        return true;
    }

    /**
     * 检查给定方法是否匹配预设的切点表达式
     *
     * @param method    需要检查的方法
     * @param targetClass 目标类
     * @return 是否匹配切点表达式
     */
    @Override
    public boolean matches(Method method, Class<?> targetClass) {
        // return pointcutExpression.matchesMethodExecution(method).alwaysMatches();
        return true;
    }

}
